using Npgsql;
using System;
using Gtk;

namespace PTransaction
{


	public partial class TransactionView : Gtk.Window
	{
		private NpgsqlConnection connection = DbConnection.Instance.Connection;
		private NpgsqlTransaction transaction;
		
		public TransactionView () : base(Gtk.WindowType.Toplevel)
		{
			
			this.Build ();
			//applyAction.Sensitive = false;
			
			//prueba();
			goForwardAction.Activated += delegate 
			{
				transaction = connection.BeginTransaction();
				labelStatus.LabelProp = "BeginTransaction";
				
			};
			executeAction.Activated += delegate 
			{
				string sql = textview.Buffer.Text;
				NpgsqlCommand command = connection.CreateCommand();
				command.CommandText = sql;
				command.CommandTimeout = 5;
				try
				{
					command.ExecuteNonQuery();
					labelStatus.LabelProp = "Command Ok";
				}
				catch(Exception e)
				{
					MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, e.Message);
					messageDialog.Run();
					messageDialog.Destroy();
					throw e;
				}
			};
			
			applyAction.Activated += delegate 
			{
				transaction.Commit();
				labelStatus.LabelProp = "Commit";
			};
			
			cancelAction.Activated += delegate 
			{
				transaction.Rollback();
				labelStatus.LabelProp = "Rollback";
			};
			
		}
		private void prueba()
		{
			//transaction = DbConnection.Instance.Connection.BeginTransaction();
			try
			{
				//	Sentencia 1
				NpgsqlCommand command1 = DbConnection.Instance.Connection.CreateCommand();
				command1.CommandText = "update articulo set precio=precio+0.1 where id=1";
				command1.ExecuteNonQuery();

				//	Sentencia 2
				NpgsqlCommand command2 = DbConnection.Instance.Connection.CreateCommand();
				command2.CommandText = "update articulo set precio=precio-0.1 where id=2";
				command2.ExecuteNonQuery();	
				
				if(command2.ExecuteNonQuery() != 1)
				{
					throw new Exception("No existe un articulo con el id=2000");
				}
				transaction.Commit();
				
			}
			catch(Exception e)
			{
				transaction.Rollback();
				//
				Console.WriteLine("Fracasó la transacción");
				MessageDialog messageDialog = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, e.Message);
				messageDialog.Run();
				messageDialog.Destroy();
			}
		}
	}
}